package org.gzc.linklist;

/**
 * @Description:
 * @Author: guozongchao
 * @Date: 2020/8/3 11:11
 */ //单链表
public  class SingleLinkList {
    private StudentNode head;

    public SingleLinkList() {
        head = new StudentNode(-1, "");
    }

    public SingleLinkList(StudentNode node) {
        this();
        head.next = node;
    }

    private void checkNotNull() {
        if (head.next == null) {
            throw new NullPointerException("链表为空");
        }
    }

    //添加结点 (尾部添加)
    public void add(StudentNode node) {
        StudentNode temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = node;
    }

    //按no查找结点
    public StudentNode get(int no) {
        checkNotNull();
        StudentNode temp = head;
        boolean found = false;
        while (temp.next != null) {
            temp = temp.next;
            if (temp.no == no) {
                found = true;   //找到
                break;
            }
        }
        if (found) {
            return new StudentNode(temp.no, temp.name);
        }
        return null;
    }

    //按no修改
    public void update(int no, String newName) {
        checkNotNull();
        StudentNode temp = head;
        boolean found = false;
        while (temp.next != null) {
            temp = temp.next;
            if (temp.no == no) {
                found = true;
                break;
            }
        }
        if (!found) {
            throw new RuntimeException("没有找到no=" + no + "的结点");
        }
        temp.name = newName;
    }

    //按照no的排序插入
    public void addByOrder(StudentNode node) {
        StudentNode temp = head;
        while (temp.next != null) {
            if (node.no < temp.next.no) {
                break;
            }
            temp = temp.next;
        }
        node.next = temp.next;
        temp.next = node;
    }

    //删除结点
    public void delete(int no) {
        checkNotNull();
        StudentNode temp = head;
        boolean found=false;
        while (temp.next != null) {
            if (no == temp.next.no) {
                found=true;
                break;
            }
            temp=temp.next;
        }
        if (!found) {
            throw new RuntimeException("没有找到no=" + no + "的结点！删除失败！");
        }
        temp.next=temp.next.next;
    }

    //获得链表的元素个数
    public int size() {
        int count=0;
        StudentNode temp=head;
        while (temp.next != null) {
            count++;
            temp=temp.next;
        }
        return count;
    }

    //遍历链表
    public void display() {
        StudentNode temp=head;
        for (int i = 0; i < size(); i++) {
            if (temp.next == null) {
                break;
            }
            temp=temp.next;
            System.out.println("第"+i+"个结点："+temp);
        }
    }

    //返回头结点
    public StudentNode getHead() {
        return head;
    }

}
